<?php
//yield作为语句来使用
//作为生成器使用
//生成器是可中断的函数，yield构成了中断点
//调用生成的对象一次，其中的代码就执行一次，因此可以用于处理数据量大的时候

require '../../app/libs/Debug.php';
$debug = new Debug();
function xrange($start, $end, $step=1) {
    for ($i=$start;$i<$end;$i+=$step) {
        yield $i;
    }
}
echo '使用系统细带的range生成100w个元素的数组' . "\n";
$debug->start();
$array = range(1, 1000000);
$debug->end();
$debug->calculation();
echo '生成的数据类型:' . gettype($array) . "\n";
echo 'use time:' . $debug->useTime . "\n";
echo 'use memory:' . $debug->useMemory . "kb\n";
echo 'use yield' . "\n";
$debug->start();
$obj = xrange(1,1000000);
$debug->end();
$debug->calculation();
echo '生成的数据类型:' . gettype($obj) . "\n";
echo 'use time:' . $debug->useTime . "\n";
echo 'use memory:' . $debug->useMemory . "kb\n";

echo '遍历用时:' . "\n";
echo 'range:' . "\n";
$debug->start();
foreach ($array as $num) {
    $num;
    //do nothing
}
$debug->end();
$debug->calculation();
echo 'use time:' . $debug->useTime . "\n";
echo 'use memory:' . $debug->useMemory . "kb\n";
echo 'yield:' . "\n";
$debug->start();
foreach ($obj as $num) {
    $num;
    //do nothing
}
$debug->end();
$debug->calculation();
echo 'use time:' . $debug->useTime . "\n";
echo 'use memory:' . $debug->useMemory . "kb\n";
exit;
if ($obj instanceof Iterator) {
    echo '$obj instance of Iterator' . "\n";
}
while ($obj->valid()) {
    echo $obj->current()."\n";
    $obj->next();
}

$debug->end();
